package org.rcy.framework.job.elastic;

import com.dangdang.ddframe.job.api.ElasticJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.api.listener.ElasticJobListener;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/12/7 17:52
 */


public class JobManager {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private final CoordinatorRegistryCenter regCenter;
	private boolean disabled = true;
	private boolean overwrite = false;
	private Map<String, JobScheduler> schedulerHolder = new LinkedHashMap();

	public JobManager(CoordinatorRegistryCenter regCenter, boolean disabled, boolean overwrite) {
		this.regCenter = regCenter;
		this.disabled = disabled;
		this.overwrite = overwrite;
	}

	public void addJob(SimpleElasticJob job) {
		Class<?> jobClass = job.getClass();
		String jobName = jobClass.getName();
		JobCoreConfiguration simpleCoreConfig = JobCoreConfiguration.newBuilder(jobName, job.getCron(), job.getShardingTotalCount()).build();
		SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(simpleCoreConfig, jobClass.getCanonicalName());
		LiteJobConfiguration simpleJobRootConfig = LiteJobConfiguration.newBuilder(simpleJobConfig).disabled(this.disabled).overwrite(this.overwrite).build();
		JobScheduler jobScheduler = new SpringJobScheduler((ElasticJob) job, this.regCenter, simpleJobRootConfig, new ElasticJobListener[0]);
		jobScheduler.init();
		this.schedulerHolder.put(jobName, jobScheduler);
		this.logger.info("Job {} scheduled.", jobName);
	}

	public Set<String> getJobNames() {
		return this.schedulerHolder.keySet();
	}

	public void remove(String jobName) {
		this.schedulerHolder.get(jobName).getSchedulerFacade().shutdownInstance();
	}
}
